/*
 * 文件名：StringTools.java
 * 版权：Copyright by www.huawei.com
 * 描述：
 * 修改人：zhu
 * 修改时间：2006-7-12
 * 跟踪单号：
 * 修改单号：
 * 修改内容：
 */

package com.kuanrf.common.tools;

import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.text.DecimalFormat;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
import java.util.regex.Pattern;

import com.kuanrf.common.KeyConstant;

/**
 * String的工具类
 *
 * @author zhu
 * @version 2006-7-12
 * @see StringTools
 * @since
 */
public class StringTools
{
    /**
     * Description: 格式化字符串(用户组建表使用) <br>
     *
     * @param name
     * @return String
     */
    public static String formatString(String name)
    {
        String s = "0000000000" + name;
        return s.substring(s.length() - 10, s.length());
    }
    
    /**
     * Description:把GBK转码成ISO8859_1 <br>
     *
     * @param name
     * @return String
     */
    public static String getStringByISO(String name)
    {
        try
        {
            // 防止中文字符出现乱码
            name = new String(name.getBytes(KeyConstant.DEFAULT_CHARSET),
                    "ISO8859_1");
        }
        catch (UnsupportedEncodingException e2)
        {
        }
        
        return name;
    }
    
    /**
     * Description:获得格式化的url <br>
     *
     * @param name
     * @return String
     */
    public static String getFormatUrl(String url)
    {
        if (isNullOrNone(url))
        {
            return "";
        }
        
        if (url.indexOf('?') == -1)
        {
            return url + '?';
        }
        else
        {
            return url + '&';
        }
    }
    
    /**
     * Description: 获得字符(byte)的实际长度<br>
     * 1、…<br>
     * 2、…<br>
     * 3、…<br>
     * 4、…<br>
     *
     * @param s
     * @return int
     * @exception/throws
     */
    public static int lengthByte(String s)
    {
        int length = 0;
        for (int i = 0; i < s.length(); i++)
        {
            if (s.charAt(i) <= 127)
            {
                length++;
            }
            else
            {
                length = length + 2;
            }
        }
        return length;
    }
    
    /**
     * Description: 在jdbc用thin客户端连接oracle里面中文算3个字符<br>
     *
     * @param s
     * @return int
     * @exception/throws
     */
    public static int lengthByteInPrepared(String s)
    {
        int length = 0;
        
        if (s == null)
        {
            return length;
        }
        
        for (int i = 0; i < s.length(); i++)
        {
            if (s.charAt(i) <= 127)
            {
                length++;
            }
            else
            {
                length = length + 3;
            }
        }
        return length;
    }
    
    /**
     * Description:判断字段空null <br>
     *
     * @param s
     * @return boolean
     */
    public static boolean isNullOrNone(String s)
    {
        if (s == null || "".equals(s.trim()))
        {
            return true;
        }
        
        return false;
    }
    
    /**
     *
     * Description: 判断对象是否为空<br>
     *
     * @param obj
     * @return boolean
     * @exception/throws [违例类型] [违例说明]
     */
    public static boolean isNullOrNone(Object obj)
    {
        if (obj == null)
        {
            return true;
        }
        if (obj instanceof String)
        {
            return isNullOrNone((String) obj);
        }
        return false;
    }
    
    /**
     * Description:判断字段空null <br>
     *
     * @param s
     * @return boolean
     */
    public static boolean isNullOrNone(String[] ss)
    {
        if (ss == null || ss.length == 0)
        {
            return true;
        }
        
        for (int i = 0; i < ss.length; i++)
        {
            if (ss[i] == null || "".equals(ss[i].trim()))
            {
                return true;
            }
        }
        
        return false;
    }
    
    /**
     * Description:判断字段空null <br>
     *
     * @param s
     * @return boolean
     */
    public static boolean isAllNullOrNone(String[] ss)
    {
        if (ss == null || ss.length == 0)
        {
            return true;
        }
        
        for (int i = 0; i < ss.length; i++)
        {
            if (ss[i] != null && !"".equals(ss[i].trim()))
            {
                return false;
            }
        }
        
        return true;
    }
    
    public static int countChar(String src, char c)
    {
        if (isNullOrNone(src))
        {
            return 0;
        }
        
        int k = 0;
        for (int i = 0; i < src.length(); i++)
        {
            if (src.charAt(i) == c)
            {
                k++;
            }
        }
        
        return k;
    }
    
    /** 
     * 把'变成 ''
     * @param src
     * @return 
     */
    public static String oracleString(String src)
    {
        if (isNullOrNone(src))
        {
            return "";
        }
        
        return src.replaceAll("'", "''");
    }
    
    /** 
     * 保护截断
     * @param s
     * @param begin
     * @param end
     * @return 
     */
    public static String truncate(String s, int begin, int end)
    {
        if (isNullOrNone(s))
        {
            return "";
        }
        
        if (begin < 0)
        {
            return "";
        }
        
        if (begin >= end)
        {
            return "";
        }
        
        s = s.trim();
        if (begin >= s.length())
        {
            return "";
        }
        
        if (end >= s.length())
        {
            return s;
        }
        else
        {
            return s.substring(begin, end);
        }
    }
    
    /**
     * <一句话功能简述>生成随机码
     * <功能详细描述>
     * @param number 生成随机码的位数
     * @return [参数说明]
     * 
     * @return String [返回类型说明]
     * @exception throws [违例类型] [违例说明]
     * @see randomCode
     */
    public static String randomCode(int number)
    {
        //生成随机码
        String verifyCode = "";
        
        for (int i = 0; i < number; i++)
        {
            Random r = new Random();
            verifyCode += String.valueOf(r.nextInt(10));
        }
        return verifyCode;
    }
    
    /**
     * 生成8位随机密码(包括大小写字母，数字)
     * <一句话功能简述>
     * <功能详细描述>
     * @param number
     * @return [参数说明]
     * 
     * @return String [返回类型说明]
     * @exception throws [违例类型] [违例说明]
     * @see [类、类#方法、类#成员]
     */
    public static String randCode(int number)
    {
        String s = "abcdebfhijkmlnopqrstuvwxyz0123456789ABCDEFHIJKMLNOPQRSTUVWXYZ";
        StringBuffer sb = new StringBuffer();
        String str = "";
        for (int i = 0; i < number; i++)
        {
            Random rd = new Random();
            //此处不能使用s.length()，只能使用s.length()-1，因为会出现数组越界异常
            int j = rd.nextInt(s.length() - 1);
            str = sb.append(s.charAt(j)).toString();
        }
        if (Pattern.compile("[a-z]+").matcher(str).find(0)
                && Pattern.compile("[A-Z]+").matcher(str).find(0)
                && Pattern.compile("[0-9]+").matcher(str).find(0))
        {
            return str;
        }
        else
        {
            return randCode(number);
        }
    }
    
    /**
     * 生成商贸易8位随机密码（系统定制），密码规则：“3个小写字母+3个数字+2个大写字母”累计8位密码长度。
     * <功能详细描述>
     * @return [参数说明]
     * 
     * @return String [返回类型说明]
     * @exception throws [违例类型] [违例说明]
     * @see [类、类#方法、类#成员]
     */
    public static String randEbsPass()
    {
        String lower_ = "abcdefghijklmnopqrstuvwxyz";
        String number_ = "0123456789";
        String upper_ = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        Random rd = new Random();
        
        StringBuffer sb = new StringBuffer();
        //3个小写
        for (int i = 0, j = 0; i < 3; i++)
        {
            j = rd.nextInt(26);
            sb.append(lower_.charAt(j));
        }
        //3个数字
        for (int i = 0, j = 0; i < 3; i++)
        {
            j = rd.nextInt(9);
            sb.append(number_.charAt(j));
        }
        //2个大写
        for (int i = 0, j = 0; i < 2; i++)
        {
            j = rd.nextInt(26);
            sb.append(upper_.charAt(j));
        }
        return sb.toString();
        
    }
    
    /**
     * 
     * Description: 判断是否为数字<br>
     * 1、…<br>
     * 2、…<br>
     * 3、…<br>
     * 4、…<br>
     *
     * @param str
     * @return boolean 
     * @exception/throws [违例类型] [违例说明]
     */
    public static boolean isNumber(String str)
    {
        if (null == str || "".equals(str))
        {
            return false;
        }
        else
        {
            return Pattern.matches("^[0-9]+$", str);
        }
    }
    
    /**
     * 
     * Description: 判断是否为数字字母<br>
     * 1、…<br>
     * 2、…<br>
     * 3、…<br>
     * 4、…<br>
     *
     * @param str
     * @return boolean 
     * @exception/throws [违例类型] [违例说明]
     */
    public static boolean isNumberOrLetter(String str)
    {
        if (null == str || "".equals(str))
        {
            return false;
        }
        else
        {
            return Pattern.matches("^[0-9A-Za-z]+$", str);
        }
    }
    
    /**
     * 
     * Description: 判断是否为数字字母或者.<br>
     * 1、…<br>
     * 2、…<br>
     * 3、…<br>
     * 4、…<br>
     *
     * @param str
     * @return boolean 
     * @exception/throws [违例类型] [违例说明]
     */
    public static boolean isNumberOrLetterOrDot(String str)
    {
        if (null == str || "".equals(str))
        {
            return false;
        }
        else
        {
            return Pattern.matches("^[.0-9A-Za-z]+$", str);
        }
    }
    
    /**
     * 
     * Description: 判断是否为金额（整数或小数后两位)<br>
     * 1、…<br>
     * 2、…<br>
     * 3、…<br>
     * 4、…<br>
     *
     * @param str
     * @return boolean 
     * @exception/throws [违例类型] [违例说明]
     */
    public static boolean isMoney(String str)
    {
        if (null == str || "".equals(str))
        {
            return false;
        }
        else
        {
            return Pattern.matches("^[0-9]+\\.{0,1}[0-9]{0,2}$", str);
        }
    }
    
    /**
     * Description: 获得字符(byte)的实际长度<br>
     * 1、…<br>
     * 2、…<br>
     * 3、…<br>
     * 4、…<br>
     *
     * @param s
     * @return int
     * @exception/throws
     */
    public static int realLength(String s)
    {
        if (null == s || "".equals(s))
        {
            return 0;
        }
        else
        {
            return s.getBytes().length;
        }
    }
    
    /**
     * Description: 检查非法字符<br>
     */
    public static boolean isUnlawfulChar(String s)
    {
        if (null == s || "".equals(s))
        {
            return false;
        }
        else
        {
            return Pattern.matches("^[^`~@#\\$%\\^&\\*\\(\\)=\\!\\+\\\\/\\|<>\\?;\\:\\.'\"\\{\\}\\[\\]??, ]*$",
                    s);
        }
    }
    
    /**
     * Description: 检查非法字符[]|~^          \\|~\\[\\]
     */
    public static boolean isUnlawfulChar2(String s)
    {
        if (s.trim().equals(""))
        {
            return false;
        }
        return Pattern.matches("^[^|\\^~\\[\\]]*$", s);
    }
    
    /**
     * 
     * Description: 判断是否为字母<br>
     * 1、…<br>
     * 2、…<br>
     * 3、…<br>
     * 4、…<br>
     *
     * @param str
     * @return boolean 
     * @exception/throws [违例类型] [违例说明]
     */
    public static boolean isLetter(String str)
    {
        if (null == str || "".equals(str))
        {
            return false;
        }
        else
        {
            return Pattern.matches("^[A-Za-z]+$", str);
        }
    }
    
    /**
     * 
     * Description: 判断是否为字母和数字<br>
     * 1、…<br>
     * 2、…<br>
     * 3、…<br>
     * 4、…<br>
     *
     * @param str
     * @return boolean 
     * @exception/throws [违例类型] [违例说明]
     */
    public static boolean isLetterOrNumber(String str)
    {
        if (null == str || "".equals(str))
        {
            return false;
        }
        else
        {
            return Pattern.matches("^[\\w]+$", str);
        }
    }
    

    
    /**
     * 把String 转换为 html格式
     * <功能详细描述>
     * @param text
     * @return [参数说明]
     * 
     * @return String [返回类型说明]
     * @exception throws [违例类型] [违例说明]
     * @see [类、类#方法、类#成员]
     */
    public static String stringextToHtmltext(String text)
    {
        text = text.replace("\n", "<br>");
        return text.replace(" ", "&nbsp;");
    }
    
    /**
     * 格式化内容为浮点型的String转化为指定格式的String
     * formatString("3.1415926","0.00") = "3.14"
     * <功能详细描述>
     * @return [参数说明]
     * 
     * @return String [返回类型说明]
     * @exception throws [违例类型] [违例说明]
     * @see [类、类#方法、类#成员]
     */
    public static String formatString(String number, String mode)
    {
        if (!Pattern.matches("^(-?\\d+)(\\.\\d+)?$", number))
        {
            return null;
        }
        DecimalFormat format = new DecimalFormat(mode);
        return format.format(Double.valueOf(number));
    }
    
    /**
     * 格式化double为指定格式的String
     * formatString(3.1415926,"0.00") = 3.14
     * <功能详细描述>
     * @return [参数说明]
     * 
     * @return String [返回类型说明]
     * @exception throws [违例类型] [违例说明]
     * @see [类、类#方法、类#成员]
     */
    public static String formatString(double number, String mode)
    {
        DecimalFormat format = new DecimalFormat(mode);
        return format.format(number);
    }
    
    public static String trim(String string, String charstr)
    {
        return string.replace(charstr, "");
    }
    
    /**
     * <一句话功能简述>
     * <功能详细描述>
     * @param obj
     * @param className
     * @return [参数说明]
     * 
     * @return String [返回类型说明]
     * @exception throws [违例类型] [违例说明]
     * @see [类、类#方法、类#成员]
     */
    public static String getWebRootPath()
    {
        String absolutePath = StringTools.class.getResource("").getPath();
        String urlRoot = "";//路径临时处理缓存 
        int pos = absolutePath.indexOf("WEB-INF");//判断根目录 
        if (pos != -1)
            urlRoot = absolutePath.substring(0, pos);
        else
            urlRoot = absolutePath.substring(0, 3);//无相关文件去盘符下 
            
        if (urlRoot.substring(urlRoot.length() - 1, urlRoot.length())
                .equals(System.getProperty("file.separator"))
                || urlRoot.substring(urlRoot.length() - 1, urlRoot.length())
                        .equals("/"))
        {
            urlRoot = urlRoot.substring(0, urlRoot.length() - 1);//除去最后的分隔符 
        }
        return urlRoot.substring(1, urlRoot.length());// 除去路径最开头的' /'
    }
    
    /**
     *  判断是否为浮点数，包括double和float  
     * <功能详细描述>
     * @param str
     * @return [参数说明]
     * 
     * @return boolean [返回类型说明]
     * @exception throws [违例类型] [违例说明]
     * @see [类、类#方法、类#成员]
     */
    public static boolean isDouble(String str)
    {
        Pattern pattern = Pattern.compile("^[-\\+]?[.\\d]*$");
        return pattern.matcher(str).matches();
    }
    
    /**
     * 字符串","隔开 转换为   List
     * <功能详细描述>
     * @param str
     * @return [参数说明]
     * 
     * @return List<String> [返回类型说明]
     * @exception throws [违例类型] [违例说明]
     * @see [类、类#方法、类#成员]
     */
    public static List<String> stringToList(String str)
    {
        List<String> list = null;
        if (!StringTools.isNullOrNone(str))
        {
            String[] array = str.split(",");
            list = Arrays.asList(array);
        }
        return list;
    }
    
    /**
     * 转换字符串为整数
     * <功能详细描述>
     * @param number
     * @return [参数说明]
     * 
     * @return int [返回类型说明]
     * @exception throws [违例类型] [违例说明]
     * @see [类、类#方法、类#成员]
     */
    public static int convertStringToInteger(String number)
    {
        int result = 0;
        try
        {
            result = Integer.valueOf(number);
        }
        catch (NumberFormatException e)
        {
            result = 0;
        }
        return result;
    }
    
    /**
     * 转换字符串为浮点数
     * <功能详细描述>
     * @param number
     * @return [参数说明]
     * 
     * @return int [返回类型说明]
     * @exception throws [违例类型] [违例说明]
     * @see [类、类#方法、类#成员]
     */
    public static double convertStringToDouble(String number)
    {
        double result = 0;
        try
        {
            result = Double.valueOf(number);
        }
        catch (NumberFormatException e)
        {
            result = 0;
        }
        return result;
    }
    
    /**
     * 是否包含英文标点
     * <功能详细描述>
     * @param str
     * @return [参数说明]Z
     * 
     * @return boolean [返回类型说明]
     * @exception throws [违例类型] [违例说明]
     * @see [类、类#方法、类#成员]
     */
    public static boolean isContainPunct(String str)
    {
        
        if (null == str || "".equals(str.trim()))
        {
            return false;
        }
        else
        {
            String pa = str.replaceAll("\\p{Punct}", "");
            if (pa.equals(str))
            {
                return false;
            }
            else
            {
                return true;
            }
        }
    }
    
    /** 判断对象是否为空
     * <功能详细描述>
     * @param obj
     * @return [参数说明]
     * 
     * @return boolean [返回类型说明]
     * @exception throws [违例类型] [违例说明]
     * @see [类、类#方法、类#成员]
     */
    public static boolean objectIsNullOrNone(Object obj)
    {
        boolean isNullOrNone = true;
        
        if (obj == null)
        {
            return true;
        }
        
        @SuppressWarnings("rawtypes")
		Class eleClassA = obj.getClass();
        Field[] fields = eleClassA.getDeclaredFields();
        if (fields == null || fields.length == 0)
        {
            return true;
        }
        
        for (Field field : fields)
        {
            @SuppressWarnings("rawtypes")
			Class propClass = field.getType();
            String propName = field.getName();
            
            field.setAccessible(true);
            Object propAValue = null;
            
            try
            {
                //根据getMethod方法来获取属性值
                String methodName = "get"
                        + Character.toUpperCase(propName.charAt(0))
                        + propName.substring(1);
                Method[] methods = eleClassA.getDeclaredMethods();
                for (Method m : methods)
                {
                    if (methodName.equals(m.getName())
                            && m.getParameterTypes().length == 0
                            && propClass.equals(m.getReturnType()))
                    {
                        propAValue = m.invoke(obj);
                        
                        if (null != propAValue)
                        {
                            return false;
                        }
                    }
                }
            }
            catch (Exception e)
            {
                continue;
            }
        }
        return isNullOrNone;
    }
    
}